

class IndexDB{
  db
  constructor(db){
    this.db = db
  }
  /**
   * 
   * @param {*} action 操作方法=> 新增:add, 读取主键:get, 更新:put, 删除:delete, 索引查询: indexGet
   * @param {*} tableName 表名 
   * @param {*} data 插入的数据 或 要查询的数据
   * @param {*} indexName 查询的索引
   */
  action(action,tableName,data,indexName){
    return new Promise((resolve,reject) => {
      let store = this.db.transaction([tableName],'readwrite').objectStore(tableName)
      let request = action === 'indexGet' ? store.index(indexName).get(data):store[action](data)
      request.onsuccess = function(){
        // console.log('数据库操作成功');
        resolve(request.result)
      }
      request.onerror = function(e){
        console.log('数据库操作失败',e.target.error);
        reject(e.target.error)
      }
    })
  }
  getAll(tableName){
    return new Promise((resolve,reject) => {
      let request = this.db.transaction([tableName],'readwrite')
      .objectStore(tableName)
      .openCursor()
      let res = []

      request.onsuccess = function(e){
        let cursor = e.target.result
        if(cursor){
          res.push(cursor.value)
          cursor.continue()
        } else {
          resolve(res)
        }
      }

      request.onerror = function(e){
        console.log('数据库操作失败',e.target.error);
        reject(e.target.error)
      }
    })
  }
}







function createIndexDB(baseName,tableName,keyPath,keysArray){
  return new Promise((resolve,reject) => {
    let indexDB = window.indexedDB;
    const request = indexDB.open(baseName, 1);
    request.onsuccess = function (event) {
      if (request.result) {
        // console.log("indexDB打开成功");
        resolve(request.result);
      } else {
        reject(event)
        console.log("indexDB打开失败");
      }
    };
  
    request.onerror = function (e) {
      reject(e)
      console.log("indexDB打开失败");
    };
  
    request.onupgradeneeded = function(e){
      let db = e.target.result
      let objectStore = db.createObjectStore(tableName, { keyPath: keyPath, autoIncrement:true })
      Array.isArray(keysArray) && keysArray.forEach((key) => {
        objectStore.createIndex(key, key, { unique: false });  // IDBObject.createIndex()的三个参数分别为索引名称、索引所在的属性、配置对象(说明该属性是否包含重复的值)。
      })
      // console.log('indexDB更新成功');
    }
  })
}

export {
  createIndexDB,
  IndexDB
}